var username = tool.getCookie('username')
if (!username) {
    layer.msg('请登录', {
        icon: 2,
        time: 1500
    }, function() {
        localStorage.setItem('url', location.href)
        location.href = "./登录.html"
    })
}
var data = localStorage.getItem('data')
if (!data) {
    $('.cart').html(`
        <div class="jumbotron" style="background-color: #eee; height: 250px; line-height: 50px; padding: 30px;">
        <h1>购物车空空如也!</h1>
        <p>去列表页挑选心意的商品</p>
        <p><a class="btn btn-primary btn-lg" href="./list.html role="button">列表页</a></p>
        </div>
    `)
} else {
    var arr = JSON.parse(data).filter(item => item.username === username)
    if (arr.length) {
        var ids = arr.map(item => item.goodsid).join()
            // console.log(ids);
        var loadindex = layer.load(1, {
            shade: [1, '#000']
        })
        $.get('./php/cart.php', { ids }, res => {
            console.log(res);
            var { meta: { status, msg }, data } = res;
            var str = '';
            data.forEach(item => {
                var number = arr.find(v => v.goodsid === item.id).number
                str += `
                <tr style="vertical-align: middle; border: none;">
                    <td><input checked type="checkbox" name="selectone"></td>
                    <td>
                        <a href="./detail.html?id=${item.id}"><img width="80px" height="80px" src="${item.imgpath.split('=====')[0]}"></a>
                    </td>
                    <td>
                        <span>${item.name}</span>
                    </td>
                    <td class="hong">￥<span class="s1">${item.price}</span></td>
                    <td class="number">
                        <button class="reduce">-</button>
                        <input type="number" value="${number}">
                        <button class="add">+</button>
                    </td>
                    <td class="hong subtotal">￥<span class="s1">${item.price * number}</span></td>
                    <td data-id="${item.id}">
                        <a href="javascript:;" class="btn removecart btn-danger">删除</a>
                    </td>
                </tr>
                `
            })
            $('.cart tbody').html(str)
            layer.close(loadindex)
                // 全选
            selectAll()
                // 单选
            selectOne()
                // 数量+
            numberAdd()
                // 数量-
            numberReduce()
                // 计算小计
            subtotal()
                // 总价格、数量
            total()
                // 删除
            removeCart()
        }, 'json')

    } else {
        $('.cart').html(`
        <div class="jumbotron" style="background-color: #eee; height: 250px; line-height: 50px; padding: 30px;">
        <h1>购物车空空如也!</h1>
        <p>去列表页挑选商品</p>
        <p><a class="btn btn-primary btn-lg" href="./list.html" role="button">列表页</a></p>
        </div>
    `)
    }
}
// 全选功能
function selectAll() {
    $('[name="selectAll"]').click(function() {
        $('[name="selectone"]').prop('checked', $(this).prop('checked'))
        $('[name="selectAll"]').prop('checked', $(this).prop('checked'))
        total()
    })
}
// 单选功能
function selectOne() {
    $('[name="selectone"]').click(function() {
        var arr = Array.prototype.slice.call($('[name="selectone"]'))
        var bool = arr.every(item => item.checked)
        $('[name="selectAll"]').prop('checked', bool)
        total()
    })
}
// 数量+
function numberAdd() {
    $('.add').click(function() {
        var number = +$(this).prev().val()
        number++
        $(this).prev().val(number);
        var data = localStorage.getItem('data')
        data = JSON.parse(data)
        var id = $(this).parent().siblings().last().attr('data-id')
        var obj = data.find(item => item.goodsid === id && item.username === username)
        obj.number++;
        localStorage.setItem('data', JSON.stringify(data))
        subtotal()
        total()
    })
}
// 数量-
function numberReduce() {
    $('.reduce').click(function() {
        var number = +$(this).next().val()
        number--
        $(this).next().val(number);
        var data = localStorage.getItem('data')
        data = JSON.parse(data)
        var id = $(this).parent().siblings().last().attr('data-id')
        var obj = data.find(item => item.goodsid === id && item.username === username)
        obj.number--;
        localStorage.setItem('data', JSON.stringify(data))
        subtotal()
        total()
    })
}
// 小计
function subtotal() {
    $('.cart .number input').each(function(i, v) {
        var sub = v.value * $(v).parent().prev().find('span').text()
        $(v).parent().next().find('span').text(sub)
    })
}
// 总数量价格
function total() {
    var totalPrice = 0;
    var totalNum = 0;
    $('[name="selectone"]:checked').each(function(i, v) {
        totalPrice += ($(this).parent().siblings('.subtotal').find('span').text() - 0)
        totalNum += ($(this).parent().siblings('.number').find('input').val() - 0)
    })
    $('.totalNum').text(totalNum)
    $('.totalPrice').text(totalPrice)
}
// 删除
function removeCart() {
    $('.removecart').click(function() {
        layer.confirm('您确定要删除吗？', {
            btn: ['确定', '取消'] //按钮
        }, () => {
            $(this).parent().parent().remove()
            total()
                // 本地数据删除
            var data = localStorage.getItem('data')
            data = JSON.parse(data)
            var id = $(this).parent().attr('data-id')
            var index = data.findIndex(item => item.goodsid === id && username === item.username)
            data.splice(index, 1)
            localStorage.setItem('data', JSON.stringify(data))
            layer.msg('删除成功', {
                time: 1500, //20s后自动关闭
                icon: 1
            });
        }, function() {
            layer.msg('取消成功', {
                time: 1500, //20s后自动关闭
                icon: 1
            });
        });

    })
}

$('.giao').click(function() {
    layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['420px', '240px'], //宽高
        content: ''
    });
})